"""
udp 服务端流程示例
"""
from socket import *
import pymysql

# 参数字典
kwargs = {
    "host":"localhost",
    "port": 3306,
    "user": "root",
    "password": "root",
    "database": "dict",
    "charset": "utf8"
}

# 连接数据库
db = pymysql.connect(**kwargs)
# 生成游标：执行sql操作数据，得到操作结果的对象
cur = db.cursor()

# 创建udp套接字
udp_socket = socket(AF_INET,SOCK_DGRAM)
# 绑定地址
udp_socket.bind(("0.0.0.0",8888))

# 先收后发
while True:
    data,addr = udp_socket.recvfrom(1024)
    try:
        sql = "select menu from dict where word = %s"
        cur.execute(sql, [data.decode()])
        fetchone = cur.fetchone()
        print(fetchone)
        print(addr, ":", data.decode())  # data->byte
        udp_socket.sendto(fetchone[0].encode(), addr)  # addr回复
    except Exception as e:
        print(e)
        db.rollback()
    else:
        db.commit()  # 提交事务

    # if data.decode() == "##":
    #     break

udp_socket.close()